import React, {useEffect, useState} from 'react'
import { Rating } from 'react-simple-star-rating'
import PropTypes from 'prop-types'
import './route-info.css'
import { useHistory } from "react-router-dom";
import {api2, getToken} from "../api.js";
import MapComp from "./map-comp.jsx";

const RouteInfo = (props) => {
  const history = useHistory();

  const [loading, setLoading] = useState(true);
  const [route, setRoute] = useState({});

  useEffect(() => {
    const fetchReview = async () => {
      try {
        const response = await api2.send('getUserReviewById', { token: getToken(), id: props.reviewId });
        if (response.success) {
          setReview(response.data);
          setRoute( response.data.route );
          setLoading(false);
        } else {
          console.error('Failed to fetch review:', response.error);
        }
      } catch (error) {
        console.error('Error fetching review:', error);
      }
    };

    fetchReview();
  }, [props.reviewId]);

  const [rating, setRating] = useState(0);
  const [review, setReview] = useState({
    id: '',
    // name: '',
    rating: '',
    title: '',
    rev_text: '',
    rev_date: new Date().toISOString().split('T')[0],
    route_id: '',
    user_id: '',
    firstPoint: '',
    firstPointDescription: '',
    public_state: false,
  });

  const handleRating = (rate) => {
    setRating(rate)
    setReview({
      ...review,
      rating: rate
    });
  }

  const handleChange = (e) => {
    const { name, value } = e.target;
    setReview({
      ...review,
      [name]: value
    });
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      const token = getToken();
      const response = await api2.send('saveReview', { ...review, token, id: props.reviewId });
      if (response.success) {
        alert('Обзор маршрута успешно сохранен');
        if (response.data && response.data.id) {
          setReview({ ...review, id: response.data.id });
        }
        //history.push('/my-reviews');
      } else {
        alert('Ошибка при сохранении обзора: ' + response.error);
      }
    } catch (error) {
      console.error('Error saving review:', error);
      alert('Произошла ошибка при сохранении обзора');
    }
  };

  const handlePublishToggle = async () => {
    try {
      const token = getToken();
      const action = review.public_state ? 'unpublishReview' : 'publishReview';
      const response = await api2.send(action, { token, reviewId: review.id });
      if (response.success) {
        const newPublicState = !review.public_state;
        setReview({ ...review, public_state: newPublicState });
        alert(newPublicState ? 'Обзор маршрута опубликован' : 'Обзор маршрута снят с публикации');
      } else {
        alert(`Ошибка при ${review.public_state ? 'снятии с публикации' : 'публикации'} обзора: ${response.error}`);
      }
    } catch (error) {
      console.error('Error toggling review publication:', error);
      alert('Произошла ошибка при изменении статуса публикации');
    }
  };

  return (
      <div
          className={`route-info-contact1 thq-section-padding ${props.rootClassName} `}
      >
        <div className="thq-section-max-width thq-flex-row route-info-max-width">
          <form className="route-info-form thq-flex-column" onSubmit={handleSubmit}>
            <div className="route-info-container">
              <div className="route-info-input">
                <label
                    htmlFor="route-name"
                    className="thq-body-small"
                >
                  Название Маршрута
                </label>
                <input
                    type="text"
                    id="route-name"
                    name="title"
                    placeholder="Маршрут"
                    className="thq-input"
                    value={review.title}
                    onChange={handleChange}
                />
              </div>
              <div className="route-info-container1">
                <div className="route-info-input1">
                  <label
                      htmlFor="route-description"
                      className="thq-body-small"
                  >
                    Общее описание маршрута
                  </label>
                  <textarea
                      id="route-description"
                      name="rev_text"
                      rows="3"
                      placeholder="Про маршрут"
                      className="thq-input"
                      value={review.rev_text}
                      onChange={handleChange}
                  ></textarea>
                </div>
              </div>
            </div>
            <div className="route-info-container2">
              <div className="route-info-input2">
                <label
                    htmlFor="contact-form-6-options"
                    className="thq-body-small"
                >
                  <span className="">Ваша оценка</span>
                  <br className=""></br>
                </label>
                <Rating
                    onClick={handleRating}
                    initialValue={rating}
                />
              </div>
            </div>
            <div className="route-info-mapinrev"></div>
            <div className="route-info-container3">
              <div className="route-info-input3">
                <label
                    htmlFor="first-point"
                    className="thq-body-small"
                >
                  <span className="">Первая точка</span>
                  <br className=""></br>
                </label>
                <input
                    type="text"
                    id="first-point"
                    name="firstPoint"
                    placeholder="Первая точка"
                    className="thq-input"
                    value={review.firstPoint}
                    onChange={handleChange}
                />
              </div>
              <div className="route-info-input4">
                <label
                    htmlFor="first-point-description"
                    className="thq-body-small"
                >
                  Описание первой точки
                </label>
                <textarea
                    id="first-point-description"
                    name="firstPointDescription"
                    rows="3"
                    placeholder="Первая точка"
                    className="thq-input"
                    value={review.firstPointDescription}
                    onChange={handleChange}
                ></textarea>
              </div>
            </div>
            <button type="submit" className="route-info-button thq-button-filled">
              <span className="thq-body-small">{props.action}</span>
            </button>
            <div className="route-info-container4">
              <button
                  type="button"
                  className="route-info-button1 thq-button-outline"
                  onClick={handlePublishToggle}
                  disabled={!review.id} // Disable if the review hasn't been saved yet
              >
              <span className="thq-body-small">
                <span className="">
                  {review.public_state ? 'Убрать из публичных' : 'Опубликовать обзор маршрута'}
                </span>
                <br></br>
              </span>
              </button>
            </div>
          </form>
          <MapComp map_type="edit" route={ route }></MapComp>
        </div>
      </div>
  )
}

RouteInfo.defaultProps = {
  action: 'Сохранить',
  rootClassName: '',
}

RouteInfo.propTypes = {
  action: PropTypes.string,
  rootClassName: PropTypes.string,
}

export default RouteInfo